package com.xiejun.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class NioClient {
    
    private static final String HOST = "localhost";
    private static final int PORT = 9000;
    
    public static void main(String[] args) {
        try {
            // 打开一个选择器
            Selector selector = Selector.open();
            
            // 打开一个套接字通道
            final SocketChannel socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false); // 设置为非阻塞模式
            
            // 连接到服务器
            boolean connected = socketChannel.connect(new InetSocketAddress(HOST, PORT));
            
            // 将套接字通道注册到选择器上
            if (connected) {
                socketChannel.register(selector, SelectionKey.OP_READ);
            } else {
                socketChannel.register(selector, SelectionKey.OP_CONNECT);
            }
            
            System.out.println("NIO Client started and connecting to " + HOST + ":" + PORT);
            
            // 启动一个线程处理用户输入
            Thread inputThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    Scanner scanner = new Scanner(System.in);
                    while (true) {
                        System.out.print("Enter message (or 'quit' to exit): ");
                        String message = scanner.nextLine();
                        if ("quit".equalsIgnoreCase(message)) {
                            try {
                                socketChannel.close();
                                System.exit(0);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        
                        // 发送消息到服务器
                        if (socketChannel.isConnected()) {
                            try {
                                ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
                                socketChannel.write(buffer);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });
            inputThread.setDaemon(true);
            inputThread.start();
            
            // 主循环处理网络事件
            while (true) {
                selector.select();
                
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
                
                while (keyIterator.hasNext()) {
                    SelectionKey key = keyIterator.next();
                    
                    if (key.isConnectable()) {
                        handleConnect(key);
                    } else if (key.isReadable()) {
                        handleRead(key);
                    }
                    
                    keyIterator.remove();
                }
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private static void handleConnect(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        
        if (socketChannel.isConnectionPending()) {
            socketChannel.finishConnect();
        }
        
        // 注册读事件
        socketChannel.register(key.selector(), SelectionKey.OP_READ);
        System.out.println("Connected to server");
    }
    
    private static void handleRead(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        
        int bytesRead = socketChannel.read(buffer);
        
        if (bytesRead > 0) {
            String receivedData = new String(buffer.array(), 0, bytesRead);
            System.out.println("Received from server: " + receivedData);
        } else if (bytesRead < 0) {
            System.out.println("Server closed the connection");
            socketChannel.close();
        }
    }
}